import { isIncludeChinese, isObject, isString } from '@/utils/is';
import { logManager } from '@/utils/log';
import { useAuthSetting } from './useAuthSetting';
import { useAppStoreWithOut } from '@/store/modules/app';
import { isNaN } from 'lodash-es';

/** 默认经纬度 深圳市中心点 */
export const DefaultCenterPoint = {
  latitude: 22.53332,
  longitude: 113.93041,
};

/**
 * @description 地址相关方法集合
 * @date 21/09/2022
 * @export
 */
export function useLocation() {
  const { showHeader, hideHeader, getPrivacySetting } = useAppStoreWithOut()

  /**
   * @description 解析接口中的地址
   * @date 21/09/2022
   * @param {string} [locationStr]
   */
  function parseAddress(locationStr?: string): UniNamespace.OpenLocationOptions {
    if (!isString(locationStr)) {
      console.error('数据格式错误 ===> ', locationStr);
      locationStr = '';
    }

    /** 验证地址字符串格式, 格式: [longitude, latitude, address, name].join(',') */
    const [longitude, latitude, address, name] = locationStr.split(',');
    return {
      longitude: Number(longitude) || NaN,
      latitude: Number(latitude) || NaN,
      address: isIncludeChinese(address) ? address : locationStr,
      name,
    };
  }

  /**
   * @description 打开地图
   * @date 21/09/2022
   * @param {string | UniNamespace.OpenLocationOptions} [locationOptions]
   */
  function openLocation(locationOptions?: string | UniNamespace.OpenLocationOptions) {
    let options: UniNamespace.OpenLocationOptions = {
      longitude: DefaultCenterPoint.longitude,
      latitude: DefaultCenterPoint.latitude,
      scale: 8,
    };

    if (isString(locationOptions)) {
      const op = parseAddress(locationOptions);
      if (op.longitude && op.latitude) {
        options = { ...options, ...op, scale: 18 };
      }
    } else if (isObject(locationOptions)) {
      options = locationOptions;
    }

    uni.openLocation({
      ...options,
      fail: (err) => {
        logManager.error(err);
        console.error(err);
      },
    });
  }

  /**
   * @description 选择地址
   * @date 22/09/2022
   * @param {(string | UniApp.ChooseLocationOptions)} op
   * @param {(address: string) => void} [success]
   */
  function chooseLocation(
    op: string | UniApp.ChooseLocationOptions,
    success?: (address: string) => void,
  ) {
    getPrivacySetting().then(() => {
      if (!op) op = '';
      let addressObj = isString(op) ? parseAddress(op) : (op as UniNamespace.ChooseLocationOptions);
      const { longitude, latitude } = addressObj;
      hideHeader()
      uni.chooseLocation({
        longitude: isNaN(longitude) ? void 0 : longitude,
        latitude: isNaN(latitude) ? void 0 : latitude,
        success: (result) => {
          let { longitude, latitude, address, name } = result;
          address = address.replace(/,/g, "-")
          name = name.replace(/,/g, "-")
          let val = [longitude, latitude, address, name].join(',');
          success?.(val);
        },
        fail: (err) => {
          console.error(err);
          logManager.error(err);
        },
        complete: () => showHeader()
      });
    })
  }

  /**
   * @description 获取当前定位
   * @date 08/02/2023
   * @returns {*}  {Promise<{ latitude: number; longitude: number }>}
   */
  function getLocation(): Promise<{ latitude: number; longitude: number }> {
    return new Promise((resolve, reject) => {
      wx.getLocation({
        isHighAccuracy: true, // 开启地图精准定位
        type: 'gcj02',
        success: ({ latitude, longitude }) => {
          resolve({ latitude, longitude });
        },
        fail: (err) => {
          console.log(err);

          // authErrorCallbak('userLocation', err);
          reject(err.errMsg);
          logManager.error(err);
        },
      });
    });
  }

  return {
    parseAddress,
    openLocation,
    chooseLocation,
    getLocation
  };
}
